<template>
  <div class="article-container">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="openAddDialog">新增文章</el-button>
    </div>
    
    <!-- 文章列表表格 -->
    <el-table :data="articleList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="标题" width="180" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="nickname" label="作者" width="120" />
      <el-table-column prop="views" label="浏览量" width="100" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '已发布' : '未发布' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button size="small" @click="viewArticle(scope.row)">查看</el-button>
          <el-button size="small" type="primary" @click="editArticle(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="confirmDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑文章对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增文章' : '编辑文章'"
      width="60%"
    >
      <el-form :model="articleForm" :rules="rules" ref="articleFormRef" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="articleForm.description" placeholder="请输入文章描述" />
        </el-form-item>
        <el-form-item label="URL" prop="url">
        <!-- 解释：
        1. prepend：在输入框前面添加内容
        2. append：在输入框后面添加内容
        3. slot：自定义输入框内容
        4. 这里使用了 prepend，在输入框前面添加了 http://
        -->
        <el-input v-model="articleForm.url" placeholder="请输入文章URL" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="articleForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入文章内容"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="articleForm.status">
            <el-radio :label="1">发布</el-radio>
            <el-radio :label="0">草稿</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看文章详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="文章详情"
      width="60%"
      destroy-on-close
    >
      <div v-if="currentArticle" class="article-detail">
        <h2 class="article-title">{{ currentArticle.title }}</h2>
        <div class="article-meta">
          <span>作者: {{ currentArticle.nickname }}</span>
          <span>发布时间: {{ formatDate(currentArticle.createTime) }}</span>
          <span>浏览量: {{ currentArticle.views }}</span>
        </div>
        <div class="article-description">
          <strong>描述:</strong> {{ currentArticle.description }}
        </div>
        <div class="article-url">
          <strong>链接:</strong> 
          <a :href="currentArticle.url" target="_blank">{{ currentArticle.url }}</a>
        </div>
        <div class="article-content">
          <strong>内容:</strong>
          <p>{{ currentArticle.content }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryPageApi, addApi, updateApi, getArticleById, deleteApi } from '../api/article'

// 文章列表数据
const articleList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 获取文章列表
const getArticleList = async () => {

    queryPageApi({
        pageNum: currentPage.value,
        pageSize: pageSize.value
    }).then(res=>{
        console.log(res)
        articleList.value = res.data.rows
        total.value = res.data.total
    })
    
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getArticleList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getArticleList()
}

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 文章表单
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const articleFormRef = ref(null)
const articleForm = reactive({
  id: null, // 文章ID，编辑时需要
  title: '',
  content: '',
  url: '',
  description: '',
  authorId: 1, // 默认作者ID，实际应该从用户信息中获取
  status: 1,
  views: 0,
  categoryId: null, // 分类ID
  nickname: '', // 作者昵称
  avatar: '' // 作者头像
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入文章描述', trigger: 'blur' }
  ],
  url: [
    { required: true, message: '请输入文章URL', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
}

// 打开新增对话框
const openAddDialog = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 查看文章详情对话框
const detailDialogVisible = ref(false)
const currentArticle = ref(null)

// 查看文章
const viewArticle = async (row) => {
  loading.value = true
  try {
    // 通过API获取完整的文章详情
    const res = await getArticleById(row.id)
    if (res && res.code === 1) {
      currentArticle.value = res.data
    } else {
      // 如果API调用失败，使用表格中的数据
      currentArticle.value = row
      ElMessage.warning('获取文章详情失败，显示部分信息')
    }
  } catch (error) {
    console.error('获取文章详情错误:', error)
    currentArticle.value = row
    ElMessage.warning('获取文章详情出错，显示部分信息')
  } finally {
    loading.value = false
    detailDialogVisible.value = true
  }
}

// 编辑文章
const editArticle = async (row) => {
  dialogType.value = 'edit'
  loading.value = true
  
  try {
    // 获取完整的文章详情用于编辑
    const res = await getArticleById(row.id)
    if (res && res.code === 1) {
      // 复制文章数据到表单
      Object.keys(articleForm).forEach(key => {
        if (key in res.data) {
          articleForm[key] = res.data[key]
        }
      })
      // 确保ID字段被正确设置
      articleForm.id = res.data.id
    } else {
      // 如果API调用失败，使用表格中的数据
      Object.keys(articleForm).forEach(key => {
        if (key in row) {
          articleForm[key] = row[key]
        }
      })
      articleForm.id = row.id
      ElMessage.warning('获取文章详情失败，使用列表数据')
    }
  } catch (error) {
    console.error('获取文章详情错误:', error)
    // 出错时使用表格中的数据
    Object.keys(articleForm).forEach(key => {
      if (key in row) {
        articleForm[key] = row[key]
      }
    })
    articleForm.id = row.id
    ElMessage.warning('获取文章详情出错，使用列表数据')
  } finally {
    loading.value = false
    dialogVisible.value = true
  }
}

// 重置表单
const resetForm = () => {
  if (articleFormRef.value) {
    articleFormRef.value.resetFields()
  }
  // 手动重置所有字段
  articleForm.id = null
  articleForm.title = ''
  articleForm.content = ''
  articleForm.url = ''
  articleForm.description = ''
  articleForm.authorId = 1
  articleForm.status = 1
  articleForm.views = 0
  articleForm.categoryId = null
  articleForm.nickname = ''
  articleForm.avatar = ''
  articleForm.createTime = null
  articleForm.updateTime = null
}

// 提交表单
const submitForm = async () => {
  if (!articleFormRef.value) return
  
  await articleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 更新时间
        articleForm.updateTime = new Date().toISOString()
        
        if (dialogType.value === 'add') {
          // 新增文章时设置创建时间
          if (!articleForm.createTime) {
            articleForm.createTime = new Date().toISOString()
          }
          // 新增文章
          const res = await addApi(articleForm)
          if (res && (res.code === 1)) {
            ElMessage.success('新增文章成功')
            dialogVisible.value = false
            getArticleList() // 刷新列表
          } else {
            ElMessage.error(res?.message || '新增文章失败')
          }
        } else {
          // 编辑文章逻辑
          const res = await updateApi(articleForm)
          if (res && (res.code === 1)) {
            ElMessage.success('编辑文章成功')
            dialogVisible.value = false
            getArticleList() // 刷新列表
          } else {
            ElMessage.error(res?.message || '编辑文章失败')
          }
        }
      } catch (error) {
        console.error('提交表单错误:', error)
        ElMessage.error('提交失败，请重试')
      }
    } else {
      return false
    }
  })
}

// 确认删除文章
const confirmDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除文章「${row.title}」吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        loading.value = true
        const res = await deleteApi(row.id)
        if (res && res.code === 1) {
          ElMessage.success('删除文章成功')
          getArticleList() // 刷新列表
        } else {
          ElMessage.error(res?.message || '删除文章失败')
        }
      } catch (error) {
        console.error('删除文章错误:', error)
        ElMessage.error('删除失败，请重试')
      } finally {
        loading.value = false
      }
    })
    .catch(() => {
      // 取消删除操作
      ElMessage.info('已取消删除')
    })
}

// 页面加载时获取文章列表
onMounted(() => {
  getArticleList()
})
</script>

<style scoped lang="less">
.article-container {
  padding: 20px;
  
  .operation-bar {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.article-detail {
  padding: 10px;
  
  .article-title {
    font-size: 22px;
    margin-bottom: 15px;
    color: #303133;
  }
  
  .article-meta {
    margin-bottom: 20px;
    color: #909399;
    font-size: 14px;
    
    span {
      margin-right: 15px;
    }
  }
  
  .article-description,
  .article-url,
  .article-content {
    margin-bottom: 15px;
    line-height: 1.6;
  }
  
  .article-content {
    background-color: #f8f8f8;
    padding: 15px;
    border-radius: 4px;
    
    p {
      white-space: pre-wrap;
      margin: 0;
    }
  }
  
  a {
    color: #409eff;
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
}
</style>